package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.cgms.service.CgmsCompanionCommentService;
import com.ucode.cgms.service.CgmsCompanionProductService;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.member.service.MemberService;
import com.ucode.model.cgms.CgmsCompanionComment;
import com.ucode.model.cgms.CgmsCompanionProduct;
import com.ucode.model.cgms.CgmsCompanionUser;
import com.ucode.model.cgms.convert.CgmsCompanionCommentConvert;
import com.ucode.model.cgms.vo.CgmsCompanionCommentVO;
import com.ucode.model.member.Member;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 管理后台 - 陪玩社区系统 - 陪玩评论控制器
 *
 * @Author: system
 * @Date: 2025/01/15 10:00
 * @Version: 1.0
 */
@Tag(name = "管理后台 - 陪玩社区系统 - 陪玩评论")
@RestController
@RequestMapping("/cgms/companion-comment")
@Validated
public class CgmsCompanionCommentController {

    @Resource
    private CgmsCompanionCommentService cgmsCompanionCommentService;
    
    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;
    
    @Resource
    private CgmsCompanionProductService cgmsCompanionProductService;
    
    @Resource
    private MemberService memberService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-comment:query')")
    public ResponseResult<Paginator<CgmsCompanionCommentVO>> pageList(
            @Schema(description = "用户ID") @RequestParam(value = "userId", required = false) Long userId,
            @Schema(description = "陪玩用户ID") @RequestParam(value = "companionUserId", required = false) Long companionUserId,
            @Schema(description = "评论内容关键词") @RequestParam(value = "content", required = false) String content,
            @Schema(description = "创建时间区间", example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]") @RequestParam(value = "createTimeInterval", required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Map<String, Object> condition = new HashMap<>();
        
        if (ObjectUtil.isNotNull(userId)) {
            condition.put("userId", userId);
        }
        
        if (ObjectUtil.isNotNull(companionUserId)) {
            condition.put("companionUserId", companionUserId);
        }
        if (StrUtil.isNotBlank(content)) {
            //模糊查询
            condition.put("content", content);
        }

        if (ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2) {
            condition.put("startTime", createTimeInterval[0]);
            condition.put("endTime", createTimeInterval[1]);
        }
        
        condition.put("deltag", false);

        return ResponseResult.success(pageList(condition, pageNum, pageSize));
    }

    @GetMapping("/getById/{id}")
    @Parameter(description = "评论ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-comment:query')")
    public ResponseResult<CgmsCompanionCommentVO> getById(@PathVariable(name = "id", required = true) Long id) {
        CgmsCompanionComment comment = cgmsCompanionCommentService.validate(id);
        CgmsCompanionCommentVO commentVO = CgmsCompanionCommentConvert.INSTANCE.convert(comment);
        
        // 填充用户信息
        if (ObjUtil.isNotEmpty(commentVO.getUserId())) {
            Member member = memberService.selectByPrimaryKey(commentVO.getUserId());
            if (ObjUtil.isNotEmpty(member)) {
                commentVO.setUserNickname(member.getNickname());
                commentVO.setUserAvatar(member.getAvatar());
            }
        }
        
        // 填充陪玩用户信息
        if (ObjUtil.isNotEmpty(commentVO.getCompanionUserId())) {
            CgmsCompanionUser companionUser = cgmsCompanionUserService.selectByPrimaryKey(commentVO.getCompanionUserId());
            if (ObjUtil.isNotEmpty(companionUser)) {
                commentVO.setCompanionUserNickname(companionUser.getNickName());
                commentVO.setCompanionUserAvatar(companionUser.getAvatar());
            }
        }
        
        // 填充商品信息
        if (ObjUtil.isNotEmpty(commentVO.getCompanionProductId())) {
            CgmsCompanionProduct product = cgmsCompanionProductService.selectByPrimaryKey(commentVO.getCompanionProductId());
            if (ObjUtil.isNotEmpty(product)) {
                commentVO.setCompanionProductName(product.getTitle());
            }
        }
        
        return ResponseResult.success(commentVO);
    }

    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description = "评论ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-comment:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name = "id", required = true) Long id) {
        // 逻辑删除
        int i = cgmsCompanionCommentService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-comment:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(
            @Schema(description = "评论ID集合", requiredMode = Schema.RequiredMode.REQUIRED)
            @NotEmpty(message = "评论ID集合不能为空")
            @Size(min = 1, max = 20, message = "评论ID集合数量为1-20条")
            @RequestParam(value = "ids", required = true) List<Long> ids) {
        int i = cgmsCompanionCommentService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success(true) : ResponseResult.failed();
    }

    /**
     * 处理分页数据
     *
     * @param condition 查询条件
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 分页结果
     */
    private Paginator<CgmsCompanionCommentVO> pageList(Map<String, Object> condition, Integer pageNum, Integer pageSize) {
        Paginator<CgmsCompanionComment> paginator = cgmsCompanionCommentService.queryPageForList(condition, pageSize, pageNum);
        return this.pageList(paginator);
    }

    /**
     * 转换分页数据并填充关联信息
     *
     * @param paginator 评论分页数据
     * @return VO分页数据
     */
    private Paginator<CgmsCompanionCommentVO> pageList(Paginator<CgmsCompanionComment> paginator) {
        Paginator<CgmsCompanionCommentVO> paginatorVO = CgmsCompanionCommentConvert.INSTANCE.convertPage(paginator);
        List<CgmsCompanionCommentVO> list = paginatorVO.getList();
        
        if (CollUtil.isNotEmpty(list)) {
            Set<Long> userIds = new HashSet<>();
            Set<Long> companionUserIds = new HashSet<>();
            Set<Long> productIds = new HashSet<>();
            
            // 收集所有ID
            for (CgmsCompanionCommentVO vo : list) {
                if (ObjectUtil.isNotEmpty(vo.getUserId())) {
                    userIds.add(vo.getUserId());
                }
                if (ObjectUtil.isNotEmpty(vo.getCompanionUserId())) {
                    companionUserIds.add(vo.getCompanionUserId());
                }
                if (ObjectUtil.isNotEmpty(vo.getCompanionProductId())) {
                    productIds.add(vo.getCompanionProductId());
                }
            }
            
            // 批量查询
            Map<Long, Member> memberMap = memberService.getMap(userIds);
            Map<Long, CgmsCompanionUser> companionUserMap = cgmsCompanionUserService.getMap(companionUserIds);
            Map<Long, CgmsCompanionProduct> productMap = cgmsCompanionProductService.getMap(productIds);
            
            // 填充数据
            for (CgmsCompanionCommentVO vo : list) {
                // 填充用户信息
                if (ObjectUtil.isNotEmpty(vo.getUserId())) {
                    Member member = memberMap.get(vo.getUserId());
                    if (ObjectUtil.isNotEmpty(member)) {
                        vo.setUserNickname(member.getNickname());
                        vo.setUserAvatar(member.getAvatar());
                    }
                }
                
                // 填充陪玩用户信息
                if (ObjectUtil.isNotEmpty(vo.getCompanionUserId())) {
                    CgmsCompanionUser companionUser = companionUserMap.get(vo.getCompanionUserId());
                    if (ObjectUtil.isNotEmpty(companionUser)) {
                        vo.setCompanionUserNickname(companionUser.getNickName());
                        vo.setCompanionUserAvatar(companionUser.getAvatar());
                    }
                }
                
                // 填充商品信息
                if (ObjectUtil.isNotEmpty(vo.getCompanionProductId())) {
                    CgmsCompanionProduct product = productMap.get(vo.getCompanionProductId());
                    if (ObjectUtil.isNotEmpty(product)) {
                        vo.setCompanionProductName(product.getTitle());
                    }
                }
            }
        }
        
        return paginatorVO;
    }
} 